#-------------------------------------------------------------------------------
# Name:		Parser for HIT2 output file
# Purpose:
#
# Author:	  bc6
#
# Created:	 06/03/2012
# Copyright:   (c) bc6 2012
# Licence:	 <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
DATABASE_NAME = 'cam930v2'
import MySQLdb

def convert_file2dictionary(filename,dictKeyField):
	fTasks=open(filename,"r")
	original_lines=fTasks.readlines()
	fTasks.close()
	original_fields=map(lambda s:s.strip('"'),original_lines[0].strip("\n").strip("\r").split("\t"))
	all_tasks=[]
	for t in original_lines[1:]:
		task_dictionary={}
		for k,v in map(None,original_fields,t.split('\t')):
			task_dictionary[k]=v.strip("\n").strip("\r").strip('"')
		all_tasks.append(task_dictionary)
	return all_tasks

def run():
	result_dict = convert_file2dictionary("amos.results","Answer.img_name")
	#print("dictionary: %s"%result_dict)
	db = MySQLdb.connect("localhost", "wustl_inst", "wustl_pass", "amos")
	cursor = db.cursor()

	for result in result_dict:
		img_name = result["Answer.img_name"]
		people = result["Answer.people"]
		if (not people == ""):
			people = people[1:]
		bikes = result["Answer.bikes"]
		if (not bikes == ""):
			bikes = bikes[1:]
		cars = result["Answer.cars"]
		if (not cars == ""):
			cars = cars[1:]
		angle = result["Answer.angle"]
		weather = result["Answer.weather"]
		season = result["Answer.season"]
		timeofday = result["Answer.timeofday"]
		workerid = result["workerid"]
		people_num = people.count(",")
		bikes_num = bikes.count(",")
		cars_num = cars.count(",")
		misc = result["Answer.misc"]

		sql ="insert into %s (img_name, people, bikes, cars, angle, weather, season, timeofday, workerid, people_num, bikes_num, cars_num, misc)\
				values ('%s', '%s', '%s', '%s','%s','%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" %\
				(DATABASE_NAME, img_name, people, bikes, cars, angle, weather, season, timeofday, workerid, people_num, bikes_num, cars_num, misc)
	   	try:
			print "executing sql statement: %s" % sql
			cursor.execute(sql)
			db.commit()
		except:
			print "error in inserting into news, rolling back"
			db.rollback()

def main():
	run()

if __name__ == '__main__':
	main()
